<template>
  <div class="student-profile">
    <el-row :gutter="20">
      <!-- 左侧栏 -->
      <el-col :span="16">
        <!-- 信息编辑卡片 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>信息编辑</span>
            </div>
          </template>

          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form
                :model="profileForm"
                :rules="profileRules"
                ref="profileFormRef"
                label-width="100px"
              >
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="profileForm.name" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="profileForm.gender">
                    <el-radio label="MALE">男</el-radio>
                    <el-radio label="FEMALE">女</el-radio>
                    <el-radio label="OTHER">其他</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    v-model="profileForm.birthday"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="身份证号" prop="idNumber">
                  <el-input v-model="profileForm.idNumber" />
                </el-form-item>
                <el-form-item label="通讯地址" prop="address">
                  <el-input
                    v-model="profileForm.address"
                    type="textarea"
                    :rows="3"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitProfileForm" :loading="savingProfile">
                    保存修改
                  </el-button>
                  <el-button @click="resetProfileForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="修改密码" name="password">
              <el-form
                :model="passwordForm"
                :rules="passwordRules"
                ref="passwordFormRef"
                label-width="100px"
              >
                <el-form-item label="当前密码" prop="currentPassword">
                  <el-input
                    v-model="passwordForm.currentPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitPasswordForm" :loading="changingPassword">
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="驾照信息" name="license">
              <el-form
                :model="licenseForm"
                :rules="licenseRules"
                ref="licenseFormRef"
                label-width="100px"
              >
                <el-form-item label="驾照类型" prop="type">
                  <el-select
                    v-model="licenseForm.type"
                    placeholder="请选择驾照类型"
                    style="width: 100%"
                    disabled
                  >
                    <el-option label="C1" value="C1" />
                    <el-option label="C2" value="C2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="报考日期" prop="applyDate">
                  <el-date-picker
                    v-model="licenseForm.applyDate"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    disabled
                  />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="学习统计" name="statistics">
              <div class="stats-grid">
                <div class="stat-item">
                  <div class="stat-value">{{ userInfo.progressPercentage }}%</div>
                  <div class="stat-label">学习进度</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ userInfo.completedHours }}</div>
                  <div class="stat-label">已完成课时</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ userInfo.totalHours }}</div>
                  <div class="stat-label">总课时</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ upcomingAppointmentsCount }}</div>
                  <div class="stat-label">待训练</div>
                </div>
              </div>

              <div class="progress-section">
                <p class="progress-title">学习进度详情</p>
                <el-progress
                  :percentage="userInfo.progressPercentage"
                  :color="progressColors"
                  :stroke-width="12"
                />
                <p class="progress-text">
                  {{ userInfo.completedHours }}/{{ userInfo.totalHours }}课时
                </p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>

      <!-- 右侧栏 -->
      <el-col :span="8">
        <!-- 个人信息卡片 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" size="small" @click="handleEditAvatar">
                更换头像
              </el-button>
            </div>
          </template>

          <div class="avatar-container">
            <el-avatar :size="120" :src="userInfo.avatar || defaultAvatar" />
            <h3>{{ userInfo.name }}</h3>
            <p class="student-id">学员ID: {{ userInfo.id }}</p>

            <el-divider />

            <el-descriptions :column="1">
              <el-descriptions-item label="注册日期">
                {{ userInfo.registerDate }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号码">
                {{ userInfo.phone }}
                <el-button type="text" @click="handleChangePhone">
                  修改
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item label="电子邮箱">
                {{ userInfo.email || '未设置' }}
                <el-button type="text" @click="handleChangeEmail">
                  {{ userInfo.email ? '修改' : '添加' }}
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item label="驾照类型">
                {{ userInfo.licenseType || '未设置' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改手机号对话框 -->
    <el-dialog v-model="phoneDialogVisible" title="修改手机号" width="400px">
      <el-form
        :model="phoneForm"
        :rules="phoneRules"
        ref="phoneFormRef"
        label-width="80px"
      >
        <el-form-item label="新手机号" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入新手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="phoneDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPhoneForm" :loading="updatingPhone">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改邮箱对话框 -->
    <el-dialog v-model="emailDialogVisible" title="修改邮箱" width="400px">
      <el-form
        :model="emailForm"
        :rules="emailRules"
        ref="emailFormRef"
        label-width="80px"
      >
        <el-form-item label="新邮箱" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入新邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="emailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEmailForm" :loading="updatingEmail">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import requestUtil from "@/util/request";
// 导入默认头像图片
import defaultAvatar from '@/assets/GGbond.png'

// 用户信息
const userInfo = ref({
  id: '',
  name: '',
  avatar: '',
  phone: '',
  email: '',
  registerDate: '',
  progressPercentage: 0,
  completedHours: 0,
  totalHours: 0,
  licenseType: ''
})

const progressColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]

// 标签页
const activeTab = ref('basic')

// 表单加载状态
const savingProfile = ref(false)
const changingPassword = ref(false)
const updatingPhone = ref(false)
const updatingEmail = ref(false)

// 待训练预约数量
const upcomingAppointmentsCount = computed(() => {
  // 这里应该从API获取实际数据，暂时返回模拟数据
  return 3
})

// 基本信息表单
const profileForm = ref({
  name: '',
  gender: '',
  birthday: '',
  idNumber: '',
  address: ''
})

const profileRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ]
}

const profileFormRef = ref(null)

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'))
  } else {
    if (passwordForm.value.confirmPassword !== '') {
      if (passwordFormRef.value) {
        passwordFormRef.value.validateField('confirmPassword')
      }
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ]
}

const passwordFormRef = ref(null)

// 驾照表单
const licenseForm = ref({
  type: '',
  applyDate: ''
})

const licenseRules = {
  type: [{ required: true, message: '请选择驾照类型', trigger: 'change' }],
  applyDate: [{ required: true, message: '请选择报考日期', trigger: 'change' }]
}

const licenseFormRef = ref(null)

// 手机号表单
const phoneForm = ref({
  phone: ''
})

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
}

const phoneFormRef = ref(null)

// 邮箱表单
const emailForm = ref({
  email: ''
})

const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const emailFormRef = ref(null)

// 对话框显示控制
const phoneDialogVisible = ref(false)
const emailDialogVisible = ref(false)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 从localStorage获取用户ID
    const userId = localStorage.getItem('user_id');

    if (!userId) {
      ElMessage.error('用户未登录或会话已过期');
      return;
    }

    const studentIdResponse = await requestUtil.get(`/student/msg/userId/${userId}`)
    const studentId = studentIdResponse.data.data.student_id

    // 获取用户信息表中的信息
    const response1 = await requestUtil.get(`/profile/msg/${userId}`)
    const data1 = response1.data

    // 获取学生信息表中的信息
    const response2 = await requestUtil.get(`/student/msg/${studentId}`)
    const data2 = response2.data.data

    // 获取用户表中的信息
    const response3 = await requestUtil.get(`/user/secret/msg/${userId}`)
    const data3 = response3.data.data[0]

    // 获取学生已完成的训练项目数量（与教练首页保持一致）
    let completedPrograms = 0;
    try {
      // 获取属于该学生的且状态为"已完成"的训练记录
      const trainingsResponse = await requestUtil.get(`/student_training/trainings/user/${userId}`)
      if (trainingsResponse.data && trainingsResponse.data.data) {
        let trainings = trainingsResponse.data.data
        // 如果返回的是分页数据结构，则使用list字段
        if (trainings.list && Array.isArray(trainings.list)) {
          trainings = trainings.list
        }
        // 过滤出状态为"已完成"的训练记录
        completedPrograms = trainings.filter(training => {
          const status = training.status?.toUpperCase()
          return status === 'COMPLETED' || status === '已完成'
        }).length
      }
    } catch (error) {
      console.warn('获取已完成项目数量失败:', error);
    }

    // 获取总的训练项目数量
    let totalPrograms = 0;
    try {
      const totalResponse = await requestUtil.get('/program/msg');
      totalPrograms = totalResponse.data.total || 0;
      console.log('Total programs count:', totalPrograms);
    } catch (error) {
      console.warn('获取总项目数量失败:', error);
    }

    // 计算进度百分比
    const progressPercentage = totalPrograms > 0 ? Math.round((completedPrograms / totalPrograms) * 100) : 0;

    // 更新用户信息
    userInfo.value = {
      id: data2.student_id || data1.user_id,
      name: data1.fullname,
      avatar: defaultAvatar,
      phone: data3.phone || '',
      email: data3.email || '',
      registerDate: data2.enrollment_date || data3.create_at || '',
      progressPercentage: progressPercentage || 0,
      completedHours: completedPrograms || 0,
      totalHours: totalPrograms || 0,
      licenseType: data2.license_type || ''
    }

    // 初始化表单数据
    profileForm.value = {
      name: data1.fullname || '',
      gender: data1.gender || '',
      birthday: data1.birthday || '',
      idNumber: data1.id_number || '',
      address: data1.address || ''
    }

    licenseForm.value = {
      type: data2.license_type || '',
      applyDate: data2.enrollment_date || '',
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'))
    console.error('获取用户信息失败:', error)
  }
}

// 提交基本信息
const submitProfileForm = () => {
  if (!profileFormRef.value) return

  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      savingProfile.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id');

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期');
          savingProfile.value = false
          return;
        }

        // 调用API保存数据
        await requestUtil.put(`/profile/update/${userId}`, {
          fullname: profileForm.value.name,
          gender: profileForm.value.gender,
          birthday: profileForm.value.birthday,
          id_number: profileForm.value.idNumber,
          address: profileForm.value.address
        });

        userInfo.value.name = profileForm.value.name

        ElMessage.success('个人信息更新成功')
        ElNotification({
          title: '成功',
          message: '个人信息已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage.error('更新失败: ' + (error.message || '未知错误'))
        console.error('更新个人信息失败:', error)
      } finally {
        savingProfile.value = false
      }
    }
  })
}

// 重置基本信息表单
const resetProfileForm = () => {
  if (profileFormRef.value) {
    profileFormRef.value.resetFields()
  }
}

// 提交密码修改
const submitPasswordForm = () => {
  if (!passwordFormRef.value) return

  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changingPassword.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id');

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期');
          changingPassword.value = false
          return;
        }
        // 获取用户当前信息，包括密码（实际应该是验证密码而不是获取明文密码）
        const userResponse = await requestUtil.get(`/user/secret/msg/${userId}`)
        const userData = userResponse.data.data[0]
        console.log('userdata:',userData.password)
         // 验证当前密码是否正确
        if (passwordForm.value.currentPassword !== userData.password) {
          ElMessage.error('当前密码不正确')
          changingPassword.value = false
          return
        }
        if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
          ElMessage.error('新密码和确认密码不一致')
          changingPassword.value = false
          return
        }
        // 调用API修改密码
        await requestUtil.put(`/user/update/${userId}`, {
          password: passwordForm.value.newPassword
        })

        ElMessage.success('密码修改成功')
        ElNotification({
          title: '安全提醒',
          message: '密码已成功修改，请妥善保管',
          type: 'success'
        })

        passwordForm.value = {
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      } catch (error) {
        ElMessage.error('密码修改失败: ' + (error.message || '未知错误'))
        console.error('密码修改失败:', error)
      } finally {
        changingPassword.value = false
      }
    }
  })
}

// 编辑头像
const handleEditAvatar = () => {
  ElMessage.info('修改头像功能开发中')
}

// 修改手机号
const handleChangePhone = () => {
  phoneForm.value.phone = userInfo.value.phone
  phoneDialogVisible.value = true
}

// 修改邮箱
const handleChangeEmail = () => {
  emailForm.value.email = userInfo.value.email
  emailDialogVisible.value = true
}

// 提交手机号修改
const submitPhoneForm = () => {
  if (!phoneFormRef.value) return

  phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      updatingPhone.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id');

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期');
          updatingPhone.value = false
          phoneDialogVisible.value = false;
          return;
        }

        // 调用API修改手机号
        await requestUtil.put(`/user/update/${userId}`, {
          phone: phoneForm.value.phone
        })

        // 更新本地显示
        userInfo.value.phone = phoneForm.value.phone
        phoneDialogVisible.value = false
        ElMessage.success('手机号修改成功')
        ElNotification({
          title: '成功',
          message: '手机号已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage.error('手机号修改失败: ' + (error.message || '未知错误'))
        console.error('手机号修改失败:', error)
      } finally {
        updatingPhone.value = false
      }
    }
  })
}

// 提交邮箱修改
const submitEmailForm = () => {
  if (!emailFormRef.value) return

  emailFormRef.value.validate(async (valid) => {
    if (valid) {
      updatingEmail.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id');

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期');
          updatingEmail.value = false
          emailDialogVisible.value = false;
          return;
        }

        // 调用API修改邮箱
        await requestUtil.put(`/user/update/${userId}`, {
          email: emailForm.value.email
        })

        // 更新本地显示
        userInfo.value.email = emailForm.value.email
        emailDialogVisible.value = false
        ElMessage.success('邮箱修改成功')
        ElNotification({
          title: '成功',
          message: '邮箱已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage.error('邮箱修改失败: ' + (error.message || '未知错误'))
        console.error('邮箱修改失败:', error)
      } finally {
        updatingEmail.value = false
      }
    }
  })
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.student-profile {
  padding: 20px;
}

.profile-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-container {
  text-align: center;
  padding: 10px;
}

.avatar-container h3 {
  margin: 15px 0 5px;
}

.student-id {
  margin: 0;
  color: #999;
  font-size: 14px;
}

/* 学习统计样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding: 10px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.progress-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.progress-title {
  margin: 0 0 15px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.progress-text {
  margin: 10px 0 0;
  font-size: 14px;
  color: #666;
  text-align: center;
}

/* 表单样式 */
.el-input-number {
  width: 120px !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-row {
    flex-direction: column;
  }

  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
